package com.zhugang.week13.hash;

import java.util.LinkedList;

/**
 * @program algorithms
 * @description: MyHashMap
 * @author: chanzhugang
 * @create: 2022/12/12 20:56
 */
public class MyHashMap {

    /**
     * 706 设计哈希映射
     * https://leetcode.cn/problems/design-hashmap/
     */

    private static final int SLOTS_COUNT = 3535;
    // 数组，类型是LinkedList
    private LinkedList<Pair>[] slots;

    public MyHashMap() {
        slots = new LinkedList[SLOTS_COUNT];
    }

    public void put(int key, int value) {
        // 映射到具体的桶的链表
        LinkedList<Pair> slot = slots[hash(key)];
        if (slot == null) {
            slots[hash(key)] = new LinkedList<>();
            slot = slots[hash(key)];
        }

        for (int i = 0; i < slot.size(); i++) {
            Pair pair = slot.get(i);
            if (pair.key == key) {
                slot.remove(i);
                break;
            }
        }
        slot.add(new Pair(key, value));
    }

    private int hash(int key) {
        return key % SLOTS_COUNT;
    }

    public int get(int key) {
        LinkedList<Pair> slot = slots[hash(key)];
        if (slot == null) {
            return -1;
        }
        for (int i = 0; i < slot.size(); i++) {
            Pair pair = slot.get(i);
            if (pair.key == key) {
                return pair.value;
            }
        }
        return -1;
    }

    public void remove(int key) {
        LinkedList<Pair> slot = slots[hash(key)];
        if (slot == null) {
            return;
        }
        for (int i = 0; i < slot.size(); i++) {
            Pair pair = slot.get(i);
            if (pair.key == key) {
                slot.remove(i);
                break;
            }
        }
    }

    private class Pair {
        public int key;
        public int value;

        public Pair(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
}